<?php
header("content-type:text/html;charset=utf8");
$pdo = new PDO("mysql:host=127.0.0.1;dbname=1607phpc;charset=utf8","root","root");
$city = $_POST['city'];
$selectsql = "select * from weather where city='$city'";
$res = $pdo->query($selectsql)->fetchAll(PDO::FETCH_ASSOC);
//判断数据库是否有此城市的天气，如果有，从数据库查询，如果没有从接口查询
if (!$res) {
	// 前台传过来的城市，调用接口查询
	$url = "http://localhost/three/tianqi/ser.php?city=$city";
	$data = file_get_contents($url);
	// print_r($data);die;
	$data = json_decode($data,true);
	$res = $data['result'];

	foreach ($res as $key => $value) {
		$week = $value['week'];
		$city = $value['citynm'];
		$temp_high = $value['temp_high'];
		$temp_low = $value['temp_low'];
		$temperature = $value['temperature'];
		$sql = "insert into weather values('','$week','$city','$temp_high','$temp_low','$temperature')";
		$pdo->exec($sql);
	}
}
echo json_encode($res);
?>